package com.mytx.search.utils;

import com.mytx.common.constant.Constant;
import com.mytx.common.pojo.CommonResult;
import com.mytx.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;

@SuppressWarnings("Duplicates")
public class PayUtils {
    private static Logger logger = LoggerFactory.getLogger(PayUtils.class);


    public static CommonResult payPrepare(String payPassword, BigDecimal amount, User user) {

        CommonResult commonResult = validatePayPassword( payPassword, amount, user);
        if (commonResult != null) {
            return commonResult;
        }

        CommonResult commonResult1 = checkBalance(user, amount);
        if (commonResult1 != null) {
            return commonResult1;
        }

        return null;
    }

    public static CommonResult validatePayPassword(String payPassword , BigDecimal amount, User user) {

        if (user.getPayLimit() == null || user.getPayPassword() == null) {
            logger.error("validatePayPassword:还没设置支付密码 uId:{}", user.getuId());
            return CommonResult.build(Constant.NEED_SETUP_PAY_PASSWORD_BEFORE, "非法请求");
        }

        if (user.getPayLimit().compareTo(amount) <0) {
            if (StringUtils.isEmpty(payPassword)) {
                logger.error("donation:缺少支付密码 uid:{}", user.getuId());
                return CommonResult.build(Constant.NO_PAY_PASSWORD, "非法请求");
            } else {
              //  String payPassword = body.getString("payPassword");
                if (!StringUtils.equals(user.getPayPassword(), DigestUtils.md5DigestAsHex(payPassword.getBytes()))) {
                    logger.error("donation支付密码错误 uid:{}", user.getuId());
                    return CommonResult.build(Constant.PAY_PASSWORD_ERROR, "支付密码错误");
                }
            }
        }
        return null;
    }

    public static CommonResult checkBalance(User user, BigDecimal payAmount) {

        if (user.getBalance() == null) {
            logger.error("offer:余额不足 uid:{},balance:{}", user.getuId(), user.getBalance());
            return CommonResult.build(Constant.BALANCE_NOT_ENOUGH, "余额不足");
        }
        BigDecimal balance = user.getBalance();
        BigDecimal deposit = BigDecimal.ZERO;
        if (user.getDeposit() != null) {
            deposit = user.getDeposit();
        }
        //如果用户账户可用余额小于支付的金额直接返回
        if (balance.subtract(deposit).compareTo(payAmount) < 0) {
            logger.error("offer:余额不足 uid:{},originalBalance:{},deposit:{},offerAmount:{}", user.getuId(), user.getBalance(), deposit, payAmount);
            return CommonResult.build(Constant.BALANCE_NOT_ENOUGH, "余额不足");
        }

        return null;
    }

}
